<template>
    <div class='workform'>
        <el-form ref='workFormRef' :model='workFormOption' :rules='WorkRules' label-width='100px' size='large'
            @submit.prevent>
            <el-form-item label='类型：' prop='t'>
                <el-radio-group :disabled="true" v-model='workFormOption.t' class='workstyle'>
                    <el-radio :value='0' size='large'>随堂作业</el-radio>
                    <el-radio :value='1' size='large'>期末考试</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label='作业名称：' prop='name'>
                <el-input :disabled="true" v-model.trim='workFormOption.name' placeholder='请输入作业名称' />
            </el-form-item>


            <el-form-item label='作业内容：' prop='content'>
                <PubEditor :wangEditReadOnly="true" :editContent='workFormOption.content' @editContentEnv='editContentEnv' @imgUrlEnv="imgUrlEnv"
                    @videoUrlEnv="videoUrlEnv" placeholder='请认真填写作业要求...'>
                </PubEditor>
            </el-form-item>


            <el-form-item  prop='files'>
                <OtherBigFile  :isHidden="false" :fileArr='workFormOption.files' ref='OtherBigFileRef' @fileArrChange='fileArrChange'>
                </OtherBigFile>
            </el-form-item>


            <el-form-item label='结束时间：' prop='end_time'>
                <el-date-picker v-model='workFormOption.end_time' type='datetime' placeholder='选择结束日期'
                :disabled="true" />
            </el-form-item>


            <el-form-item label='发布时间：' prop='release_time'>
                <el-radio-group v-model='workFormOption.mode' class='poststyle'>
                    <el-radio :disabled="true" :value='false' size='large'>立即发布</el-radio>
                    <el-radio :disabled="true" :value='true' size='large'>定时发布</el-radio>
                </el-radio-group>

                <template v-if='workFormOption.mode'>
                    <el-date-picker v-model='workFormOption.release_time' type='datetime' placeholder='选择日期和时间'
                    :disabled="true" />
                </template>

            </el-form-item>


        </el-form>
    </div>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import PubEditor from '@/components/PubEditor/index.vue';
import OtherBigFile from '@/components/OtherBigFile/index.vue';
import dayjs from "dayjs";
import counterStore from "@/store/modules/counter";
const imgUrlArr = ref([])

const videoUrlArr = ref([])
const { proxy } = getCurrentInstance();

const OtherBigFileRef = ref();

const isDisabled = ref(false)
const props = defineProps({
    rowData: {
        type: Object,

    }
});



const emits = defineEmits(['update:dialogVisible', 'resetData']);
//作业表结构
const workFormOption = ref({
    name: '',       //作业名称
    end_time: '',        //结束时间
    content: '',    //富文本内容
    t: 0,      //作业类型（0/1）
    mode: false,//发布类型  立即发布/定时发布 （true false）
    release_time: null, //发布时间
    files: [],  //大附件数组
    bk_id: counterStore().bkItem.id,
});

watch(() => workFormOption.value.mode, (nv) => {
    console.log(nv);
    if (nv == false) {
        workFormOption.value.release_time = null;
        WorkRules.value.release_time = [];
        proxy.$refs['workFormRef'].clearValidate(['release_time']);
    } else if (nv == true) {
        WorkRules.value.release_time = [
            { required: true, message: '定时发布时间必选', trigger: 'change' },
        ];
    }
});
//如果修改传值，修改作业表结构
if (props.rowData) {

    console.log(props.rowData);

    workFormOption.value = props.rowData
    isDisabled.value = true

    // 回显图像和视频
    workFormOption.value.content = workFormOption.value.content.replace(/\[file_id: (\d+),url: (.+?\.(jpg|png|webp|svg|gif).*?)\]/g, '<img src="$2" alt="[file_id: $1,url: $2]"/>');

    workFormOption.value.content = workFormOption.value.content.replace(/<div data-w-e-type="video" data-w-e-is-void>\s*\[file_id:\s*(\d+),url:\s*([^[\]]+)\]\s*<\/div>/g, '<video poster="[file_id: $1,url: $2]" src="$2"></video>');


    // // 去除多余的符号
    workFormOption.value.content = workFormOption.value.content.replace(/>" data-href="?" style="?"\//g, '');
}


console.log(workFormOption.value.content);


//表结构验证规则



const WorkRules = ref({
    t: [
        {
            required: true,
            message: '类型必须选择',
            trigger: 'blur',
        },
    ],
    name: [
        { required: true, message: '作业名称必须填写', trigger: 'blur' },
        { min: 3, max: 30, message: '作业名称需3-30字间', trigger: 'blur' },
    ],
    content: [
        { required: true, message: '作业内容必须填写', trigger: 'blur' },
    ],
    end_time: [
        { required: true, message: '作业结束时间必选', trigger: 'change' },
    ],

});


//大附件内容改变
const fileArrChange = (e) => {
    workFormOption.value.files = e;
};

// 获取上传图像成功的Url
const imgUrlEnv = (e) => {
    console.log(e);

    imgUrlArr.value.push(e)
}

// 获取上传视频成功的url

const videoUrlEnv = (e) => {
    videoUrlArr.value.push(e)

}






//获取富文本返回的内容
const editContentEnv = (e) => {
    if (e == '<p><br></p>') {
        e = ''
    }
    workFormOption.value.content = e;


    if (workFormOption.value.content) {
        proxy.$refs['workFormRef'].clearValidate(['content']);
    }
    // 将上传成功的图像和视频的[file_id: ${res.file_id},url: ${tem_url.value}]地址分别放在alt和poster属性中
    console.log(e);
 // 新增索引映射函数，建立匹配位置与上传文件的对应关系
 const processMediaAttributes = (content, urlArr, regex, attrName) => {
  let index = 0;
  return content.replace(regex, (match) => {
    // 只替换对应序号的属性值
    if (index < urlArr.value.length) {
      const replacement = `${attrName}="${urlArr.value[index++]}"`;
      return match.replace(/(alt|poster)=".*?"/, replacement);
    }
    return match;
  });
};

// 使用示例
if (imgUrlArr.value.length > 0 || videoUrlArr.value.length > 0) {
  // 分步骤处理不同媒体类型
  // 处理图片alt属性（按上传顺序逐个替换）
  workFormOption.value.content = processMediaAttributes(
    workFormOption.value.content,
    imgUrlArr,
    /<img[^>]*alt="[^"]*"[^>]*>/g,
    "alt"
  );

  // 处理视频poster属性（按上传顺序逐个替换）
  workFormOption.value.content = processMediaAttributes(
    workFormOption.value.content,
    videoUrlArr,
    /<video[^>]*poster="[^"]*"[^>]*>/g,
    "poster"
  );
}



};


</script>




<style>
.el-button.is-text {
    /* 隐藏“此刻”按钮，注意这里的类名可能会根据Element Plus的版本有所不同 */
    display: none;
}

.el-upload {
    display: block;
}

.el-upload-dragger {
    width: 100%;
    height: 400px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
}
</style>

<style lang='scss' scoped>
.myedit {
    width: 100%;
}


.workform {
    padding: 0 30px;

    .fileList {
        display: flex;
        flex-wrap: wrap;

        .item {
            padding-right: 30px;
            display: flex;
            align-items: center;
            font-size: 14px;
            position: relative;

            .coloricon {
                font-size: 18px;
                margin-right: 5px;
            }

            .close {
                font-size: 20px;
                color: #FF5733;
                position: absolute;
                right: 8px;
                top: 0px;
                display: none;
                cursor: pointer;
            }

            &:hover {
                .close {
                    display: block;
                }
            }
        }

    }
}

.popCover {
    min-height: 400px;
}

.poststyle {
    margin-right: 20px;
}

.addBan {
    padding: 0 30px;

    .el-form-item {
        padding: 5px 0;
    }

    .cover {
        display: flex;
    }

    .upload {
        width: 200px;
        height: 113px;

        .cover-uploader {
            width: 100%;
            height: 100%;
            border: 1px dashed #ccc;
            border-radius: 6px;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;
            position: relative;
            cursor: pointer;

            .view {
                img {
                    width: 100%;
                    height: 100%;
                    display: block;
                }

                div {
                    font-size: 14px;
                    color: #999
                }
            }

            .ceng {
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.7);
                color: #fff;
                position: absolute;
                top: 0;
                left: 0;
                display: flex;
                justify-content: center;
                align-items: center;
                opacity: 0;

                .iconfont {
                    font-size: 40px;
                }
            }

        }

        .cover-uploader:hover {
            border-color: #4395FF;

            .ceng {
                opacity: 1;
            }
        }
    }

    .text {
        padding-left: 30px;
        line-height: 1.7em;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .top {
            font-size: 16px;
            color: #4395FF;
            cursor: pointer;

            .iconfont {
                font-size: 22px;
                vertical-align: middle;
            }
        }

        .top:hover {
            color: #175CEB;
        }

        .btm {
            font-size: 13px;
            color: #999;
        }
    }

    .btngroup {
        padding-top: 30px;
    }
}
</style>